//
//  HAHomeViewController.m
//  HorsemanApp
//
//  Created by qyc on 2019/7/26.
//  Copyright © 2019 q. All rights reserved.
//
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

#import "HAHomeViewController.h"
#import "HAUserViewController.h"
#import "HAQrCodeViewController.h"

#import "RCNoDataShowView.h"
#import "HAOrderTableViewCell.h"
#import "HAOrderFinishTableViewCell.h"

#import "HAOrderModel.h"

#import "CommentTool.h"

@interface HAHomeViewController ()< CLLocationManagerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *stayDeliveryButton; // 待送达
@property (weak, nonatomic) IBOutlet UILabel *stayDeliveryLabel;
@property (weak, nonatomic) IBOutlet UIView *stayDeliveryView;
@property (weak, nonatomic) IBOutlet UIButton *alreadyDeliveryButton; // 已送达
@property (weak, nonatomic) IBOutlet UILabel *alreadyDeliveryLabel;
@property (weak, nonatomic) IBOutlet UIView *alreadyDeliveryView;
@property (weak, nonatomic) IBOutlet UIButton *userButton; // 用户

@property (strong, nonatomic) RCNoDataShowView *noDataShowView;

@property (strong, nonatomic) CLLocationManager *locationManager;

@property (assign, nonatomic) HAUserOrderType type;

@end

@implementation HAHomeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    // 请求数据
    [self addLoadListData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.tableView.estimatedRowHeight = 190;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.type = HAUserOrderTypeWithWaitDelivery;
    
    //版本更新
    [CommentTool upVersionViewWithController:self];
    // 上拉加载下拉刷新
    [self addRefresh];
    // 没数据图
    [self addNoDataShow];
    // 增加实时定位
//    [self addLocationManager];
    // Do any additional setup after loading the view from its nib.
}

// 去我的
- (IBAction)userSender:(id)sender {
    HAUserViewController *vc = [[HAUserViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 扫一扫
- (IBAction)sweepSender:(id)sender {
    HAQrCodeViewController *vc = [[HAQrCodeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

// 切换不同按钮
- (IBAction)switchSender:(id)sender {
    UIButton *btn = (UIButton *)sender;
    
    self.type = btn.tag;
    // 请求数据
    [self addLoadListData];
    
    switch (self.type) {
        case HAUserOrderTypeWithWaitDelivery:// 待送达
            self.stayDeliveryLabel.textColor = UIColorFromRGB(0xffffff);
            self.stayDeliveryLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
            self.stayDeliveryView.hidden = NO;
            
            self.alreadyDeliveryLabel.textColor = UIColorFromRGB(0xCFCFCF);
            self.alreadyDeliveryLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
            self.alreadyDeliveryView.hidden = YES;
            
            break;
        case HAUserOrderTypeWithAlreadyDelivery: // 已送达
            self.stayDeliveryLabel.textColor = UIColorFromRGB(0xCFCFCF);
            self.stayDeliveryLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
            self.stayDeliveryView.hidden = YES;
            
            self.alreadyDeliveryLabel.textColor = UIColorFromRGB(0xFFFFFF);
            self.alreadyDeliveryLabel.font = [UIFont fontWithName:@"PingFangSC-Semibold" size:16];
            self.alreadyDeliveryView.hidden = NO;
            break;
        default:
            break;
    }
}

// 数据
- (void)addLoadListData {
    
    WEAK(weakSelf, self);
    
    [[HAUserAppApi sharedApi] requestRiderOrderListWithRider_uid:[[ReadWriteUserInfoTool sharedUserInfo] getUserId] types:self.type completionHandler:^(id  _Nullable successHandler) {
        
        weakSelf.dataArray = [HAOrderModel mj_objectArrayWithKeyValuesArray:successHandler];
        
        // 无数据展示
        if (weakSelf.dataArray.count > 0) {
            weakSelf.noDataShowView.hidden = YES;
        } else {
            weakSelf.noDataShowView.hidden = NO;
        }
        
        [weakSelf.tableView reloadData];
        
    } errorHandler:^(id  _Nullable errorHandler) {
        
    }];
}

// 没有数据
- (void)addNoDataShow {
    self.noDataShowView = [[[NSBundle mainBundle] loadNibNamed:@"RCNoDataShowView" owner:nil options:nil]lastObject];
    self.noDataShowView.frame = CGRectMake(0, kWindowH/2 - 130, kWindowW, 200);
    self.noDataShowView.titlesLabel.text = @"暂无订单";
    self.noDataShowView.baseImageView.image = [UIImage imageNamed:@"zwpj"];
    self.noDataShowView.hidden = YES;
    [self.view addSubview:self.noDataShowView];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAK(weakSelf, self);
    
    if (self.type == HAUserOrderTypeWithWaitDelivery) {
        static NSString *cellIdentifier = @"HAOrderTableViewCell";
        HAOrderTableViewCell *cell = (HAOrderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"HAOrderTableViewCell" owner:self options:nil];
            cell = [array firstObject];
        }
        
        HAOrderModel *model = self.dataArray[indexPath.row];
        [cell createCellDataWithModel:model];
        cell.goSelect = ^(NSInteger tag) {
            switch (tag) {
                case 1000:
                    // 导航
                    [weakSelf whereGoMapClickWithModel:model];
                    break;
                case 1001:
                    // 联系
                    [weakSelf contactClickWithModel:model];
                    break;
                case 1002:
                    // 状态
                    [weakSelf stateClickWithModel:model];
                    break;
                default:
                    break;
            }
        };
        return cell;
    } else {
        static NSString *cellIdentifier = @"HAOrderFinishTableViewCell";
        HAOrderFinishTableViewCell *cell = (HAOrderFinishTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"HAOrderFinishTableViewCell" owner:self options:nil];
            cell = [array firstObject];
        }
        
        HAOrderModel *model = self.dataArray[indexPath.row];
        [cell createCellDataWithModel:model];
        
        if (indexPath.row != 0) {
            cell.topView.hidden = YES;
            cell.topViewHeight.constant = 0.00;
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    // 获取用户位置的对象
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"%@纬度:%f 经度:%f",[NSDate date],coordinate.latitude, coordinate.longitude);
}

/**
 上拉加载下拉刷新
 */
-(void)addRefresh {
    WEAK(weakSelf, self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        //请求页面数据
        [weakSelf addLoadListData];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

// 增加实时定位
- (void) addLocationManager {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //若不设置 app会在进入后台20分钟后停止
    self.locationManager.pausesLocationUpdatesAutomatically = NO;
    //distanceFilter是距离过滤器，为了减少对定位装置的轮询次数，位置的改变不会每次都去通知委托，而是在移动了足够的距离时才通知委托程
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    
    [self findLocation];
}

// 找到骑手位置
- (void)findLocation {
    
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        NSLog(@"requestAlwaysAuthorization");
        [self.locationManager requestAlwaysAuthorization];
    }
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        self.locationManager.allowsBackgroundLocationUpdates = YES;
    }
    
    [self.locationManager startUpdatingLocation];
    NSLog(@"start location");
}

// 更改订单状态
- (void)stateClickWithModel:(HAOrderModel *)model {
    
    NSString *titles;
    UserOrderProductStatusType order_status;
    if (model.order_status == UserOrdersProductTypeWithExpressageDelivery) {
        titles = @"是否已送达仓库";
        order_status = UserOrdersProductTypeWithReturnGoodPut;
    }
    if (model.order_status == UserOrdersProductTypeWithHorsemanReceiving) {
        titles = @"是否已送达";
        order_status = UserOrdersProductTypeWithDistributionSuccess;
    }
    
    WEAK(weakSelf, self);
    
    UIAlertController *exitController = [UIAlertController alertControllerWithTitle:@"提示" message:titles preferredStyle:UIAlertControllerStyleAlert];
    [exitController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[HAUserAppApi sharedApi] requestRiderUpdateOrderStatusWithOrder_status:order_status order_id:[NSString stringWithFormat:@"%ld",model.Id] rider_uid:[[ReadWriteUserInfoTool sharedUserInfo]getUserId] completionHandler:^(id  _Nonnull successHandler) {
            [CustomProgressHUD showMessage:@"送达成功" time:0];
            [weakSelf addLoadListData];
        } errorHandler:^(id  _Nonnull errorHandler) {
            
        }];
        
    }]];
    [exitController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:exitController animated:YES completion:nil];
}

// 点击联系
- (void)contactClickWithModel:(HAOrderModel *)model {
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",model.address.tel];[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:nil];
}

// 点击地图
- (void)whereGoMapClickWithModel:(HAOrderModel *)model {
    
    NSArray *maps = [self getInstalledMapAppWithEndLocation:CLLocationCoordinate2DMake(model.address.wei,model.address.jing) address:model.address_data.name];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"导航" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
          NSLog(@"点击取消");
    }]];

    for (int i= 0; i<maps.count; i++) {
      NSMutableDictionary *mapDic = maps[i];
      [alertController addAction:[UIAlertAction actionWithTitle:mapDic[@"title"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            if (i == 0) {  // 苹果地图
                [self navAppleMapWithModel:model];
                return;
            }
            NSDictionary *dic = maps[i];
            NSString *urlString = dic[@"url"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];

      }]];
    }

    [self presentViewController:alertController animated:YES completion:nil];
}

//苹果地图
- (void)navAppleMapWithModel:(HAOrderModel *)model {
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(model.address.wei, model.address.jing) addressDictionary:@{@"title":model.address_data.name}];
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:placemark];
    toLocation.name = model.address_data.name;
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}


#pragma mark - 导航方法
- (NSArray *)getInstalledMapAppWithEndLocation:(CLLocationCoordinate2D)endLocation address:(NSString *)address {
    NSMutableArray *maps = [NSMutableArray array];
    
    //苹果地图
    NSMutableDictionary *iosMapDic = [NSMutableDictionary dictionary];
    iosMapDic[@"title"] = @"苹果地图";
    [maps addObject:iosMapDic];
    
    //百度地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]){
        NSMutableDictionary *baiduMapDic = [NSMutableDictionary dictionary];
        baiduMapDic[@"title"] = @"百度地图";
        NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=%@&latlng:%f,%f|name=%@&mode=riding&coord_type=gcj02", address, endLocation.latitude, endLocation.longitude, address] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        baiduMapDic[@"url"] = urlString;
        [maps addObject:baiduMapDic];
    }
    
    //高德地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
        NSMutableDictionary *gaodeMapDic = [NSMutableDictionary dictionary];
        gaodeMapDic[@"title"] = @"高德地图";
        NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=%@&dname=%@&dlat=%f&dlon=%f&dev=0&t=3",@"aduo", address, endLocation.latitude, endLocation.longitude] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        gaodeMapDic[@"url"] = urlString;
        [maps addObject:gaodeMapDic];
    }
    
    //腾讯地图
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"qqmap://"]]) {
        NSMutableDictionary *qqMapDic = [NSMutableDictionary dictionary];
        qqMapDic[@"title"] = @"腾讯地图";
        NSString *urlString = [[NSString stringWithFormat:@"qqmap://map/routeplan?type=bike&from=我的位置&tocoord=%f,%f&to=%@", endLocation.latitude,  endLocation.longitude, address] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        qqMapDic[@"url"] = urlString;
        [maps addObject:qqMapDic];
    }
    
    return maps;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
